#include "stdafx.h"
#include "torrent/MetaInfo.hpp"

#include <iostream>
#include <sstream>
#include <boost/filesystem.hpp>

#include "bencode/bencode.h"
#include "torrent/bencode_helper.hpp"
#include "torrent/utility.hpp"

#if defined(_WIN32) && defined(_DEBUG)
#define new MYDEBUG_NEW
#endif

namespace torrent {

void MetaInfo::dump()
{
	std::cout << "\nInfoHash : " << std::endl;
	for (size_t i = 0; i < _infoHash.length(); ++i)
		printf("%02x ", static_cast<unsigned char>(_infoHash.at(i)));
	std::cout << "\n" << std::endl;
	std::cout << "Urlencoded InfoHash : " << std::endl;
	std::cout << _urlencodedInfoHash << "\n" << std::endl;
}

size_t MetaInfo::getPieceLength(size_t idxPiece)
{	
	if ( idxPiece == getNumPieces()-1 )
	{
		size_t length = static_cast<size_t>( getTotalFilesLength() % _info._pieceLength);
		return (length == 0 ? _info._pieceLength : length);
	}

	return static_cast<size_t>(_info._pieceLength);
}

size_t MetaInfo::getNumPieces()
{
	return static_cast<size_t>(ceil(_info._pieces.size()/20.0));
}

boost::filesystem::wpath MetaInfo::Info::File::getPath() const
{
	boost::filesystem::wpath filePath;
	for (std::vector<std::string>::const_iterator i = _path.begin(); i != _path.end(); ++i)
		filePath /= utility::mbs_to_wcs(*i);
	return filePath;
}

}
